import type Fetch from '../Fetch';
import type { Options, PluginReturn, Timeout } from '../index.type';
import { useRef } from 'react';
export function useLoadingDelayPlugin<TData = any, TRunArgs extends any[] = any[]>(fetchInstance: Fetch<TData, TRunArgs>, options: Options<TData, TRunArgs>): PluginReturn<TData, TRunArgs> {
  const { loadingDelay } = options; //设置 loading 变成 true 的延迟时间
  const timerRef = useRef<Timeout>();

  if (!loadingDelay) {
    return {};
  }

  function clearTimer() {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }
  }

  return {
    onBefore: () => {
      clearTimer();
      timerRef.current = setTimeout(() => {
        fetchInstance.setState({ loading: true });
      }, loadingDelay);
      return {
        loading: false,
      };
    },
    onFinally: () => {
      clearTimer();
    },
  };
}